package com.example.a13001.shoppingmalltemplate.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.adapters.AffirmOrderLvAdapter;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.event.AddShopCarEvent;
import com.example.a13001.shoppingmalltemplate.modle.Address;
import com.example.a13001.shoppingmalltemplate.modle.CloaseAccount;
import com.example.a13001.shoppingmalltemplate.modle.CommonResult;
import com.example.a13001.shoppingmalltemplate.modle.IntegralCloaseAccount;
import com.example.a13001.shoppingmalltemplate.modle.MyCouponList;
import com.example.a13001.shoppingmalltemplate.modle.RefreshYunFei;
import com.example.a13001.shoppingmalltemplate.mvpview.AffirmOrderView;
import com.example.a13001.shoppingmalltemplate.presenter.AffirmOrderPredenter;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AffirmOrderActivity extends BaseActivity {

    @BindView(R.id.lv_affirmorder)
    ListView lvAffirmorder;
    @BindView(R.id.iv_title_back)
    ImageView ivTitleBack;
    @BindView(R.id.ll_affirmorder_address)
    LinearLayout llAffirmorderAddress;
    @BindView(R.id.tv_title_center)
    TextView tvTitleCenter;
    @BindView(R.id.tv_doorder_total)
    TextView tvDoorderTotal;
    @BindView(R.id.tv_affirmorder_payway)
    TextView tvAffirmorderPayway;
    @BindView(R.id.ll_affirmorder_payway)
    LinearLayout llAffirmorderPayway;
    @BindView(R.id.tv_affirmorder_delivergoodsway)
    TextView tvAffirmorderDelivergoodsway;
    @BindView(R.id.ll_affirmorder_delivergoodsway)
    LinearLayout llAffirmorderDelivergoodsway;
    @BindView(R.id.tv_affirmorder_invoiceway)
    TextView tvAffirmorderInvoiceway;
    @BindView(R.id.ll_affirmorder_invoiceway)
    LinearLayout llAffirmorderInvoiceway;
    @BindView(R.id.et_doorder_say)
    EditText etDoorderSay;
    @BindView(R.id.tv_doorder_youhui)
    TextView tvDoorderYouhui;
    @BindView(R.id.tv_doorder_yunfei)
    TextView tvDoorderYunfei;
    @BindView(R.id.tv_doorder_heji)
    TextView tvDoorderHeji;
    @BindView(R.id.btn_affirmorder_commit)
    Button btnAffirmorderCommit;
    @BindView(R.id.ll_noaddress)
    LinearLayout llNoaddress;
    @BindView(R.id.ll_haveaddress)
    LinearLayout llHaveaddress;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_affirmorder_default)
    TextView tvAffirmorderDefault;
    @BindView(R.id.tv_useraddress)
    TextView tvUseraddress;
    @BindView(R.id.tv_affirmorder_invoicetitle)
    TextView tvAffirmorderInvoicetitle;
    @BindView(R.id.tv_affirmorder_money)
    TextView tvAffirmorderMoney;
    @BindView(R.id.ll_affirmorder_coupon)
    LinearLayout llAffirmorderCoupon;

    private AffirmOrderLvAdapter mAdapter;
    private List<CloaseAccount.ShopListBean> mList;
    private String mCartId;
    private static final String TAG = "AffirmOrderActivity";
    AffirmOrderPredenter affirmOrderPredenter = new AffirmOrderPredenter(AffirmOrderActivity.this);
    CloaseAccount mCloaseAccount;
    IntegralCloaseAccount mIntegralCloaseAccount;
    private int pageindex = 1;
    private String code;
    private String timestamp;
    private int addressid = 0;
    private String paymentname = "";
    private String orderType = "";
    private int invoiceStatus = -1;
    private String invoicename = "";
    private String remark = "";
    private double dd;
    private String totalPrice;
    private String paytype;
    private String snph = "";
    private int qmoney;
    private int couponStatus;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_affirm_order);
        ButterKnife.bind(this);
        affirmOrderPredenter.onCreate();
        affirmOrderPredenter.attachView(affirmOrderView);
        initData();
    }



    AffirmOrderView affirmOrderView = new AffirmOrderView() {
        @Override
        public void onSuccessDoCloaseAccount(CloaseAccount cloaseAccount) {
            Log.e(TAG, "onSuccessDoCloaseAccount: " + cloaseAccount.toString());
            mCloaseAccount = cloaseAccount;
            int status = cloaseAccount.getStatus();
            if (status > 0) {
                affirmOrderPredenter.getMyCouponList(AppConstants.COMPANY_ID, code, timestamp, "", String.valueOf(mCloaseAccount.getTotalZongPrice()), "1", AppConstants.PAGE_SIZE, pageindex);


                mList.addAll(cloaseAccount.getShopList());
                mAdapter.notifyDataSetChanged();
                DecimalFormat df = new DecimalFormat("0.00");
                String ss = df.format(cloaseAccount.getTotalZongPrice());
                if (".00".equals(ss)) {
                    tvDoorderTotal.setText("¥0.00" + "");
                } else {
                    tvDoorderTotal.setText("¥" + ss + "");
                }
                String ss1 = df.format(cloaseAccount.getTotalZkPrice());
                if (".00".equals(ss1)) {
                    tvDoorderYouhui.setText("-¥0.00" + "");
                } else {
                    tvDoorderYouhui.setText("-¥" + ss1 + "");
                }

                String payway = cloaseAccount.getPaymentTypeList().get(0).getPaymentName();
                if (!TextUtils.isEmpty(payway)) {
                    tvAffirmorderPayway.setText(payway);
                    paymentname = cloaseAccount.getPaymentTypeList().get(0).getPaymentName();

                }
                String deliverway = cloaseAccount.getExpress().get(0).getKdname();
                if (!TextUtils.isEmpty(deliverway)) {
                    tvAffirmorderDelivergoodsway.setText(deliverway);
                    orderType = deliverway;
                }
                String ss3 = df.format(cloaseAccount.getExpress().get(0).getKdYfPrice());
                if (".00".equals(ss3)) {
                    tvDoorderYunfei.setText("+¥0.00");
                } else {
                    tvDoorderYunfei.setText("+¥" + ss3);
                }
                dd = cloaseAccount.getTotalZongPrice();
                String ss2 = df.format(cloaseAccount.getTotalZongPrice() + cloaseAccount.getExpress().get(0).getKdYfPrice());

                if (".00".equals(ss2)) {
                    tvDoorderHeji.setText("¥0.00" + "");
                    totalPrice = "0.00";
                } else {
                    totalPrice = ss2;
                    tvDoorderHeji.setText("¥" + ss2 + "");
                }


            } else {
                Toast.makeText(AffirmOrderActivity.this, "" + cloaseAccount.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }
        }


        //提交商品订单
        @Override
        public void onSuccessDoCommitOrder(CommonResult commonResult) {
            Log.e(TAG, "onSuccessDoCommitOrder: " + commonResult.toString());
            int status = commonResult.getStatus();
            if (status > 0) {
                EventBus.getDefault().post(new AddShopCarEvent("提交订单成功"));
                Intent intent3 = new Intent(AffirmOrderActivity.this, OnLinePayActivity.class);
                intent3.putExtra("orderNumber", commonResult.getOrderNumber());
                intent3.putExtra("totalprice", totalPrice);
                intent3.putExtra("payid", commonResult.getPaymentId());
                startActivity(intent3);
                finish();
            } else {
                Toast.makeText(AffirmOrderActivity.this, "" + commonResult.getReturnMsg(), Toast.LENGTH_SHORT).show();
            }

        }

        //获取默认收货地址
        @Override
        public void onSuccessGetAddress(Address address) {
            Log.e(TAG, "onSuccessGetAddress: " + address.toString());
            int status = address.getStatus();
            if (status > 0) {
                llHaveaddress.setVisibility(View.VISIBLE);
                llNoaddress.setVisibility(View.GONE);
                tvUsername.setText(address.getDelivery_AddressList().get(0).getAddressName() + "    " + address.getDelivery_AddressList().get(0).getAddressPhone());
                tvUseraddress.setText("地址:" + address.getDelivery_AddressList().get(0).getAddressProvince() + address.getDelivery_AddressList().get(0).getAddressCity() + address.getDelivery_AddressList().get(0).getAddressArea() + address.getDelivery_AddressList().get(0).getAddressXX());
                addressid = address.getDelivery_AddressList().get(0).getAddresslId();
            } else {
                llHaveaddress.setVisibility(View.GONE);
                llNoaddress.setVisibility(View.VISIBLE);
            }
        }
        //得到可用优惠券列表
        @Override
        public void onSuccessGetMyCouponList(MyCouponList myCouponList) {
            Log.e(TAG, "onSuccessGetMyCouponList: "+myCouponList.toString());
            int status=myCouponList.getStatus();
            if (status>0){
                couponStatus=1;
            }else{
                couponStatus=0;
                tvAffirmorderMoney.setText("无可用优惠券");
            }
        }

        @Override
        public void onSuccessRefreshYunFei(RefreshYunFei refreshYunFei) {
            Log.e(TAG, "onSuccessRefreshYunFei: "+refreshYunFei.toString() );
            int status=refreshYunFei.getStatus();
            if (status>0){
                if (mList != null) {
                    mList.clear();
                }
                affirmOrderPredenter.doCloaseAccount(AppConstants.COMPANY_ID, code, timestamp, mCartId, AppConstants.FROM_MOBILE);
                String fangshi=tvAffirmorderDelivergoodsway.getText().toString().trim();
                List<RefreshYunFei.ExpressBean> express = refreshYunFei.getExpress();
                for (int i = 0; i < express.size(); i++) {
                    if (fangshi.equals(express.get(i).getKdname())){
                        DecimalFormat df = new DecimalFormat(".00");
                        String ss = df.format(express.get(i).getKdYfPrice());
                        if (".00".equals(ss)) {
                            tvDoorderYunfei.setText("+¥0.00");
                        } else {
                            tvDoorderYunfei.setText("+¥" + ss);
                        }
                    }
                }

            }else{

            }
        }

        @Override
        public void onError(String result) {

        }
    };

    /**
     * 初始化数据源
     */
    private void initData() {
        mCartId = getIntent().getStringExtra("cartId");
        tvTitleCenter.setText("确认订单");
        mList = new ArrayList<>();
        mAdapter = new AffirmOrderLvAdapter(AffirmOrderActivity.this, mList);
        lvAffirmorder.setAdapter(mAdapter);
        String safetyCode = MyUtils.getMetaValue(AffirmOrderActivity.this, "safetyCode");
        code = Utils.md5(safetyCode + Utils.getTimeStamp());
        timestamp = Utils.getTimeStamp();
        Log.e(TAG, "initData: " + code + "==" + Utils.getTimeStamp() + "==" + mCartId);
        affirmOrderPredenter.doCloaseAccount(AppConstants.COMPANY_ID, code, timestamp, mCartId, AppConstants.FROM_MOBILE);
        affirmOrderPredenter.getAdressList(AppConstants.COMPANY_ID, code, timestamp, AppConstants.PAGE_SIZE, pageindex, 1, "");
    }


    @OnClick({R.id.ll_affirmorder_coupon,R.id.iv_title_back, R.id.ll_affirmorder_address, R.id.ll_affirmorder_payway, R.id.ll_affirmorder_delivergoodsway, R.id.ll_affirmorder_invoiceway, R.id.btn_affirmorder_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //返回
            case R.id.iv_title_back:
                onBackPressed();
                break;

            //地址
            case R.id.ll_affirmorder_address:
                Intent addressintent = new Intent(AffirmOrderActivity.this, AdressManagerActivity.class);
                startActivityForResult(addressintent, 4);
                break;
            //支付方式
            case R.id.ll_affirmorder_payway:
                Intent intent = new Intent(AffirmOrderActivity.this, PaymentWayActivity.class);
                intent.putExtra("payway", (Serializable) mCloaseAccount.getPaymentTypeList());
                startActivityForResult(intent, 1);
                break;
            //送货方式
            case R.id.ll_affirmorder_delivergoodsway:
                Intent intent1 = new Intent(AffirmOrderActivity.this, DeliverGoodsWayActivity.class);
                intent1.putExtra("deliverway", (Serializable) mCloaseAccount.getExpress());
                startActivityForResult(intent1, 2);
                break;
            //发票信息
            case R.id.ll_affirmorder_invoiceway:
                Intent intent2 = new Intent(AffirmOrderActivity.this, InvoiceWayActivity.class);
                startActivityForResult(intent2, 3);
                break;
            //提交订单
            case R.id.btn_affirmorder_commit:
                if (addressid == 0) {
                    Toast.makeText(this, "请先选择收货地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                String invoiveway = tvAffirmorderInvoiceway.getText().toString().trim();
                if ("不开发票".equals(invoiveway)) {//是否开票发票 1 不开发票 2 给个人开发票 3 给企业开发票
                    invoiceStatus = 1;
                } else if ("个人".equals(invoiveway)){
                    invoiceStatus = 2;
                    invoicename = tvAffirmorderInvoicetitle.getText().toString().trim();
                }else{
                    invoiceStatus = 3;
                    invoicename = tvAffirmorderInvoicetitle.getText().toString().trim();
                }
                remark = etDoorderSay.getText().toString().trim();
                Log.e(TAG, "onViewClicked: " + AppConstants.COMPANY_ID + "code==" + code + "timestamp==" + timestamp + "mCartId=="
                        + mCartId + "addressid==" + addressid + "paymentid==" + paymentname + "orderType==" + orderType + "invoiceStatus==" + invoiceStatus
                        + "invoicename==" + invoicename + "remark==" + remark + "from==" + AppConstants.FROM_MOBILE+"=snph="+snph);
                affirmOrderPredenter.doCommitOrder(AppConstants.COMPANY_ID, code, timestamp, mCartId, addressid, paymentname, orderType, invoiceStatus, invoicename, snph, remark, AppConstants.FROM_MOBILE);

                break;
                //优惠券
            case R.id.ll_affirmorder_coupon:
                if (couponStatus>0){
                    Intent intent3=new Intent(AffirmOrderActivity.this,CanUseCouponActivity.class);
                    intent3.putExtra("money",mCloaseAccount.getTotalZongPrice());
                    startActivityForResult(intent3,5);
                }

                break;
        }
    }

    @OnClick()
    public void onViewClicked() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case 1:
                    if (resultCode == 11) {
                        CloaseAccount.PaymentTypeListBean closae = (CloaseAccount.PaymentTypeListBean) data.getSerializableExtra("paywayobj");
                        tvAffirmorderPayway.setText(closae.getPaymentName() != null ? closae.getPaymentName() : "");
                        paymentname = closae.getPaymentName();
                        paytype = closae.getPaymentName();
                    }
                    break;
                case 2:
                    if (resultCode == 22) {
                        CloaseAccount.ExpressBean closae = (CloaseAccount.ExpressBean) data.getSerializableExtra("deliverwayobj");
                        tvAffirmorderDelivergoodsway.setText(closae.getKdname() != null ? closae.getKdname() : "");
                        orderType = closae.getKdname() != null ? closae.getKdname() : "";
                        DecimalFormat df = new DecimalFormat(".00");
                        String ss = df.format(closae.getKdYfPrice());
                        if (".00".equals(ss)) {
                            tvDoorderYunfei.setText("+¥0.00");
                        } else {
                            tvDoorderYunfei.setText("+¥" + ss);
                        }
                        String ss2 = df.format(dd + closae.getKdYfPrice());
                        if (".00".equals(ss2)) {
                            tvDoorderHeji.setText("¥0.00" + "");
                            totalPrice = "0.00";
                        } else {
                            totalPrice = ss2;
                            tvDoorderHeji.setText("¥" + ss2 + "");
                        }
                    }
                    break;
                case 3:
                    if (resultCode == 33) {
                        String invoicetype = data.getStringExtra("invoicetype");
                        String invoicetitle = data.getStringExtra("invoicetitle");
                        if (TextUtils.isEmpty(invoicetitle)) {
                            tvAffirmorderInvoiceway.setText(invoicetype);
                            tvAffirmorderInvoicetitle.setVisibility(View.GONE);
                        } else {
                            tvAffirmorderInvoiceway.setText(invoicetype);
                            tvAffirmorderInvoicetitle.setVisibility(View.VISIBLE);
                            tvAffirmorderInvoicetitle.setText(invoicetitle);
                        }
                    }
                    break;
                case 4:
                    if (resultCode == 44) {
                        Address.DeliveryAddressListBean addressListBean = (Address.DeliveryAddressListBean) data.getParcelableExtra("address");
                        Log.e(TAG, "onActivityResult: " + addressListBean.toString());
                        tvUsername.setText(addressListBean.getAddressName() + "    " + addressListBean.getAddressPhone());
                        tvUseraddress.setText("地址:" + addressListBean.getAddressProvince() + addressListBean.getAddressCity() + addressListBean.getAddressArea() + addressListBean.getAddressXX());
                        boolean isDefault = addressListBean.isAddressDefault();
                        if (isDefault) {
                            tvAffirmorderDefault.setVisibility(View.VISIBLE);
                        } else {
                            tvAffirmorderDefault.setVisibility(View.GONE);
                        }
                        addressid = addressListBean.getAddresslId();
                        affirmOrderPredenter.refreshYunFei(AppConstants.COMPANY_ID,code,timestamp,mCartId, String.valueOf(addressid));

                    }
                    break;
                    //优惠券
                case 5:
                    if (resultCode == 55) {
                        snph=data.getStringExtra("snph");
                        qmoney=data.getIntExtra("qmoney",0);
                        tvAffirmorderMoney.setText("-¥"+qmoney);
                    }

                    break;
            }
        }

    }


//    private void showPopUpWindow() {
//        View contentView = LayoutInflater.from(AffirmOrderActivity.this).inflate(R.layout.item_pay, null);
//        final PopupWindow popWnd = new PopupWindow(AffirmOrderActivity.this);
//        popWnd.setContentView(contentView);
////    popWnd.setWidth(263);
////    popWnd.setHeight(320);
//        popWnd.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
//        popWnd.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//        final CheckBox mCbPayWechat = (CheckBox) contentView.findViewById(R.id.cb_pay_wechat);
//        final CheckBox mCbPayAli = (CheckBox) contentView.findViewById(R.id.cb_pay_ali);
//        Button mBtnConfig = (Button) contentView.findViewById(R.id.btn_pay_config);
//        mBtnConfig.setText("确认支付¥"+mCloaseAccount.getTotalZongPrice());
//        //支付宝支付
//        mCbPayAli.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                if (b) {
//                    mCbPayWechat.setChecked(false);
//                }
//            }
//        });
//        //微信支付
//        mCbPayWechat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                if (b) {
//                    mCbPayAli.setChecked(false);
//                }
//            }
//        });
//        //确认支付
//        mBtnConfig.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (!mCbPayAli.isChecked() && !mCbPayWechat.isChecked()) {
//                    Toast.makeText(AffirmOrderActivity.this, "请选择支付方式", Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
//        popWnd.setTouchable(true);
//        popWnd.setFocusable(true);
//        popWnd.setOutsideTouchable(true);
//        popWnd.setBackgroundDrawable(new BitmapDrawable(getResources(), (Bitmap) null));
//        backgroundAlpha(0.6f);
//
//        //添加pop窗口关闭事件
//        popWnd.setOnDismissListener(new poponDismissListener());
//
//        popWnd.setTouchInterceptor(new View.OnTouchListener() {
//            public boolean onTouch(View v, MotionEvent event) {
//                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
//                    popWnd.dismiss();
//                    return true;
//                }
//                return false;
//            }
//        });
//
//        //popWnd.showAsDropDown(mTvLine, 200, 0);
//        popWnd.showAtLocation(AffirmOrderActivity.this.findViewById(R.id.btn_doorder_commit),
//                Gravity.BOTTOM, 0, 0);
//
//    }


    /**
     * 添加弹出的popWin关闭的事件，主要是为了将背景透明度改回来
     *
     * @author cg
     */
//    class poponDismissListener implements PopupWindow.OnDismissListener {
//
//        @Override
//        public void onDismiss() {
//            // TODO Auto-generated method stub
//            //Log.v("List_noteTypeActivity:", "我是关闭事件");
//            backgroundAlpha(1f);
//        }
//
//    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
//    public void backgroundAlpha(float bgAlpha) {
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        lp.alpha = bgAlpha; //0.0-1.0
//        getWindow().setAttributes(lp);
//    }
}
